package com.lancoo.edu.platform.operation.backupRestore.service.timer.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import com.lancoo.edu.platform.operation.backupRestore.service.timer.ScheduleTask;
import com.lancoo.edu.platform.operation.commons.config.LancooConfig;
import com.lancoo.edu.platform.operation.commons.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lzh
 * @date 2024/6/21 17:22
 * @description 删除备份文件任务
 */
@AllArgsConstructor
@Slf4j
public class DeleteBackupJob implements Job {


    private final LancooConfig lancooConfig;
    private final ScheduleTask scheduleTask;

    /**
     * 删除备份文件任务
     *
     * @param context JobExecutionContext
     * @throws JobExecutionException JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 1、获取触发器名（任务ID）
        String group = context.getTrigger().getKey().getGroup();
        String taskId = context.getTrigger().getKey().getName();
        if (scheduleTask.beExecute(group, taskId)) {
            return;
        }
        // 1、30天前的日期
        DateTime beginOfDayFor30DaysAgo = DateUtil.offsetDay(DateUtil.beginOfDay(new Date()), -lancooConfig.getDeleteBackupDays());
        // 2、获取备份文件夹下所有文件
        List<File> fileList = new ArrayList<>();
        FileUtil.getAllFile(lancooConfig.getBackSavePath(), fileList);
        // 3、循环删除
        for (File file : fileList) {
            if (file.isFile()) {
                String name = file.getName();
                name = name.substring(name.lastIndexOf("_") + 1);
                name = name.substring(0, name.lastIndexOf("."));
                DateTime dateTime = DateUtil.beginOfDay(DateUtil.parse(name, DatePattern.PURE_DATETIME_PATTERN));
                // 删除30天前的备份文件
                if (dateTime.isBeforeOrEquals(beginOfDayFor30DaysAgo)) {
                    boolean delete = file.delete();
                    log.info("【删除备份文件{}：{}】", delete ? "成功" : "失败", file.getName());
                }
            }
        }
    }
}
